package com.csx.framework.springboot.sample.mvc.controller;

import com.csx.framework.springboot.sample.mvc.exception.CustomHandlerExceptionResolver;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 专门用于处理异常的处理器
 * @author cuisongxu
 * @date 2023/8/16 周三 15:16
 */

@RestController
public class CustomExceptionHandlerController implements ErrorController {

    /**
     * 自定义 /error 处理器的异常处理逻辑
     * 如果某些异常没有处理器,则会走到 /error 这一个默认处理器进行处理.
     */
    @RequestMapping("/error")
    @ResponseBody
    public String error(Model model, HttpServletRequest req, HttpServletResponse response) {

        Object customErrorMsgKey = model.getAttribute("customErrorMsgKey");
        // 获取错误状态码
        Exception exception = (Exception) req.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        Integer statusCode = (Integer) req.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        // 在这里实现您的自定义异常处理逻辑
        String errorMessage = "An error occurred";
        if (statusCode != null) {
            if (statusCode == 404) {
                errorMessage = "404. Page not found";
            } else if (statusCode == 500) {
                errorMessage = "500. Internal server error";
            }
            // 可根据需要添加更多状态码的处理
        }

        // 从异常对象中取出异常信息
        if(exception != null) {
            errorMessage = exception.getMessage();
        }

        return errorMessage;
    }

    /**
     * 参考 {@link CustomHandlerExceptionResolver}
     */
    @RequestMapping("/myErrorView")
    @ResponseBody
    public String myErrorView(HttpServletRequest req, HttpServletResponse response) {

        return "myErrorView";
    }
}
